package bin_tree.leetcode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 层序遍历
 **/
public class Num102 {
        public List<List<Integer>> levelOrder(TreeNode root) {
                List<List<Integer>> ret = new ArrayList<>();
                if (root == null) {
                        return ret;
                }
                // 借助队列来实现遍历过程
                Deque<TreeNode> queue = new LinkedList<>();
                queue.offer(root);
                while (!queue.isEmpty()) {
                        // 使用curList数组来保存当前层的元素
                        List<Integer> curList = new ArrayList<>();
                        // 取出当前层的所有元素添加进curList中
                        int size = queue.size();
                        for (int i = 0; i < size; i++) {
                                TreeNode cur = queue.poll();
                                curList.add(cur.val);
                                if (cur.left != null) {
                                        queue.offer(cur.left);
                                }
                                if (cur.right != null) {
                                        queue.offer(cur.right);
                                }
                        }
                        ret.add(curList);
                }
                return ret;
        }
}